package com.xin.data.simbapesa.analysis.libs

import android.app.Application
import android.content.Context
import android.os.Build
import com.adjust.sdk.Adjust
import com.google.gson.Gson
import com.xin.data.simbapesa.PathMaping
import com.xin.data.simbapesa.SimbaApp
import com.xin.data.simbapesa.api.U
import com.xin.data.simbapesa.base.BaseParams
import com.xin.data.simbapesa.utils.LogUtil
import com.xin.data.simbapesa.utils.SpUtils
import java.util.Locale

object FirebaseLib {

    // 未在线上打包时，这行代码关掉
//    private val _analytics: FirebaseAnalytics = Firebase.analytics
    private var _appId: String = ""
    private var _ga4Id: String = ""
    private var _msgToken: String = ""

    fun fetch(context: Application, onSuccess: (String) -> Unit) {
        // 未在线上打包时，这块代码关掉
//        try {
//            if (_appId.isBlank()) {
//                FirebaseAnalytics.getInstance(context).firebaseInstanceId.let {
//                    _appId = it + ""
//                    println("_appId=$_appId")
//                }
//            }
//
//            if (_ga4Id.isBlank()) {
//                FirebaseAnalytics.getInstance(context).appInstanceId.addOnSuccessListener { id ->
//                    _ga4Id = id ?: ""
//                    println("_ga4Id=$_ga4Id")
//                    onSuccess.invoke(params(context))
//                }
//            } else {
//                onSuccess.invoke(params(context))
//            }
//        } catch (e: Exception) {
//            //
//        }

        // 在线上打包时，这块代码关掉
        onSuccess.invoke(params(context))
    }

    fun addEvent(event: IEvent) {
        // 未在线上打包时，这块代码关掉
//        try {
//            _analytics.logEvent(
//                when (event) {
//                    IEvent.REGISTER -> FirebaseAnalytics.Event.SIGN_UP
//                    IEvent.APPLY -> FirebaseAnalytics.Event.PURCHASE
//                }
//            ) {
//                when (event) {
//                    IEvent.REGISTER -> {
//                        param(FirebaseAnalytics.Param.METHOD, IEvent.REGISTER.name)
//                    }
//
//                    IEvent.APPLY -> {
//                        param(FirebaseAnalytics.Param.CONTENT_TYPE, IEvent.APPLY.name)
//                        param(FirebaseAnalytics.Param.AFFILIATION, IEvent.APPLY.name)
//                        param(FirebaseAnalytics.Param.COUPON, IEvent.APPLY.name)
//                        param(FirebaseAnalytics.Param.TRANSACTION_ID, IEvent.APPLY.name)
//                        param(FirebaseAnalytics.Param.VALUE, "1")
//                        param(FirebaseAnalytics.Param.SHIPPING, "1")
//                        param(FirebaseAnalytics.Param.TAX, "1")
//                        param(FirebaseAnalytics.Param.CURRENCY, "USD")
//                    }
//                }
//            }
//        } catch (e: Exception) {
//            e.printStackTrace()
//        }
    }

    fun params(context: Context): String {
        val token = SpUtils.get_string(SimbaApp.getInstance(), SpUtils.KEY_TOKEN, "")
        val data = hashMapOf(
            "product" to U.URL_MAIN_PRODUCT, // TODO: 补充产品名
            "path" to PathMaping.PathList[30], // TODO: 补充映射
            "token" to token, // TODO: 补充token
            "advertiser_tracking_enabled" to context.packageName,
            "OSAndVersion" to "Android ${Build.VERSION.RELEASE}",
            "locale" to Locale.getDefault().toString(),
            "device" to (Build.MODEL ?: ""),
            "appVersion" to appVersionCode(context).toString(),
            "sdkVersion" to appVersionCode(context).toString(),
            "build" to "Build/${Build.ID}",
            "firebaseAppId" to _appId,
            "ga4AppInstanceId" to _ga4Id,
            "firebaseToken" to _msgToken,
            "androidId" to AdIdLib.androidId(),
            "advertId" to AdIdLib.adId(),
            "lat" to AdIdLib.adEnabled().toString(),
            "aduid" to AdIdLib.adId(),
            "aduidPath" to AdIdLib.androidId(),
            "version" to BaseParams.getVersion(SimbaApp.getInstance()),
            "apiVersion" to "v3"
        )
        LogUtil.e("me", "FirebaseLib data->$data")
        return Gson().toJson(data).trim()
    }

    fun updateNewToken(application: Application, token: String) {
        _msgToken = token
        Adjust.setPushToken(token, application)
    }

    private fun appVersionCode(context: Context): Long {
        return try {
            val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                packageInfo.longVersionCode
            } else {
                @Suppress("DEPRECATION")
                packageInfo.versionCode.toLong()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            -1
        }
    }
}